import React from 'react';
import { Card, Descriptions, Table } from 'antd';
import SearchTable from '@/components/common/SearchTable';
import { connect } from 'dva';
import { getDicByKey } from '@/support/common';

import PropTypes from 'prop-types';
import MaskText from '@/components/MaskText';

@connect((state: any) => ({
  vehicleInfo: state.vehicleInfo,
  loading: state.loading.effects['vehicleInfo/getDataWithRes'],
  vehicle: state.vehicle,
  menu: state.menu,
}))
export default class VehicleTab extends React.Component<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.object,
  };
  constructor(props: any) {
    super(props);
    this.state = {
      data: {
        vin: '',
        brandName: '',
        seriesName: '',
        styleName: '',
        styleId: '',
        colorName: '',
        licence: '',
        dealerName: '',
        pdsn: '',
        tbox: '',
        iccid: this.props.vehicleInfo.iccid ? this.props.vehicleInfo.iccid : '',
        createDate: '',
        availableDate: '',
        carSpt: '',
        enrollDate: '',
        vhlType: '',
        pageParams: {
          curPage: 1,
          pageSize: 10,
        },

      },
    };
  }
  componentDidMount() {
    this.getDetail();
    const { menu: { userProfile, dataPermission, permissions } } = this.props;
    const isS31 = permissions.includes("/deviceManager/vehicle/vehicle-forS31");//是否为S31用户
    if (isS31) {
      this.getInfo();
    }
  }
  componentWillUnmount = () => {
    this.setState = (state, callback) => {
      return;
    };
  };

  onSource = (page, size, args) =>
    new Promise(async resolve => {
      const { vehicleInfo } = this.props;

      const res = await this.props.dispatch({
        type: 'vehicleInfo/getFetchPage',
        payload: {
          url: '/vehicle/vehicleactivaterecord',
          vin: vehicleInfo.vin,

          ...args,
        },
      });

      if (res && res.statusCode === '0') {
        let a1 = 1;

        let arrayNew: any = [];
        res.data.map(item => {
          arrayNew.push(Object.assign({}, item, { sid: a1++ }));
        });

        resolve({
          data: arrayNew,
        });
      } else {
        resolve({
          total: 0,
          data: [],
        });
      }
    });

  getDetail() {
    const { vehicleInfo } = this.props;
    const { dispatch } = this.props;

    vehicleInfo.vin
      ? dispatch({
        type: 'vehicleInfo/getDataWithRes',
        payload: {
          url: '/vehicle/vehiclefinddetail',
          vin: vehicleInfo.vin,
        },

        callback: response => {
          if (response && response.statusCode == '0' && response.data) {
            this.setState({
              data: Object.assign(this.state.data, response.data),
            });
          }
        },
      })
      : '';
  }
  //获取调拨历史
  getInfo = () => {
    const { dispatch, vehicleInfo } = this.props;
    let curPage;
    let pageSize;
    if (this.state.pageParams?.curPage && this.state.pageParams?.pageSize) {
      curPage = this.state.pageParams?.curPage;
      pageSize = this.state.pageParams?.pageSize;
    } else {
      curPage = 1;
      pageSize = 10;
    }
    const obj = {
      vin: vehicleInfo.vin,
      curPage: curPage,
      pageSize: pageSize,
    };
    dispatch({
      type: 'vehicle/queryList',
      payload: obj,
    });
  }
  // 分页时触发
  tableOnChange = (pagination: any) => {
    this.setState(
      {
        pageParams: {
          curPage: pagination.current,
          pageSize: pagination.pageSize,
        },
      },
      () => {
        this.getInfo();
      },
    );
  };


  render() {
    const { context } = this;
    const { data } = this.state;
    const { loading } = this.props;
    const { vehicleInfo, vehicle: { recordList, pagination, } } = this.props;
    const {
      menu: { dicData, permissions },
    } = this.props;
    const isS31 = permissions.includes("/deviceManager/vehicle/vehicle-forS31");//是否为S31用户
    const columns = [
      {
        title: '序号',
        dataIndex: 'sid',
      },
      {
        title: '激活时间',
        dataIndex: 'activateTime',
      },
      {
        title: '激活类型',
        dataIndex: 'activateType',
        render: (text: any, record: any, index: any) => {
          return text ? getDicByKey(context.dicData, 'fenceVhlType', text.toString()) : '';
        },
      },
      {
        title: '是否二网车辆',
        dataIndex: 'isOwnToSecond',
        render: (text: any) => {
          return text === 'null' ? (text ? '是' : '否') : '';
        },
      },
      {
        title: '二网地址',
        dataIndex: 'secondUrl',
        render(val: any) {
          return <MaskText text={val} type="location" />;
        },
      },
      {
        title: '截止时间',
        dataIndex: 'expireTime',
      },
    ];
    const columnsB = [
      {
        title: 'NO',
        dataIndex: 'index',
        render: (text: any, record: any, index: any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        },
      },
      {
        title: '调出网点名称',
        dataIndex: 'outDealerNo',
      },
      {
        title: '调出网点编码',
        dataIndex: 'outDealerName',
      },
      {
        title: '调入网点名称',
        dataIndex: 'inDealerName',
      },
      {
        title: '调入网点编码',
        dataIndex: 'inDealerNo',
      },
      {
        title: '调拨时间',
        dataIndex: 'orderDate',
      },
      {
        title: '调拨状态',
        dataIndex: 'status',
        render: (text: any) => {
          switch (String(text)) {
            case '1':
              return '正常';
            case '2':
              return '异常';
            default:
              break;
          }
          return text;
        }
      },
      {
        title: '备注',
        dataIndex: 'description',
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    return (
      <>
        <Card bordered={false} loading={loading}>
          <Descriptions bordered size="small" style={{ overflow: 'hidden' }}>
            <Descriptions.Item label="VIN码">{data.vin}</Descriptions.Item>
            <Descriptions.Item label="品牌">{data.brandName}</Descriptions.Item>
            <Descriptions.Item label="车系">{data.seriesName}</Descriptions.Item>
            <Descriptions.Item label="车型">{data.styleName}</Descriptions.Item>
            <Descriptions.Item label="车型编码">{data.styleId}</Descriptions.Item>
            <Descriptions.Item label="颜色">{data.colorName}</Descriptions.Item>
            <Descriptions.Item label="车牌号码">
              <MaskText text={data.licence} type="plate" />
            </Descriptions.Item>
            <Descriptions.Item label="经销商名称">{data.dealerName}</Descriptions.Item>
            <Descriptions.Item label="车机编号">{vehicleInfo.pdsn}</Descriptions.Item>
            <Descriptions.Item label="TBOX编号">{vehicleInfo.tbox}</Descriptions.Item>
            <Descriptions.Item label="ICCID">{data.iccid}</Descriptions.Item>
            <Descriptions.Item label="入库时间">{data.createDate}</Descriptions.Item>
            <Descriptions.Item label="销售时间">{data.availableDate}</Descriptions.Item>
            <Descriptions.Item label="网联类型">
              {data.carSpt && data.carSpt === '1' ? '手机' : '传统'}
            </Descriptions.Item>
            <Descriptions.Item label="激活时间">{data.enrollDate}</Descriptions.Item>
            <Descriptions.Item label="激活类型">
              {data.vhlType
                ? getDicByKey(context.dicData, 'fenceVhlType', data.vhlType.toString())
                : ''}
            </Descriptions.Item>
            <Descriptions.Item label=""></Descriptions.Item>
          </Descriptions>
        </Card>
        <Card title="激活历史记录" bordered={false}>
          <SearchTable
            tableProps={{
              rowKey: 'sid',
              scroll: { x: true },
              columns: columns,
              onSource: this.onSource,
            }}
          />
        </Card>
        {isS31 ? (
          <Card title="调拨历史记录" bordered={false}>
            <Table
              rowKey={(record: any) => record.sid}
              dataSource={recordList || []}
              columns={columnsB}
              pagination={paginationProps}
              onChange={this.tableOnChange}
              scroll={{ x: 'max-content' }}
            />
          </Card>
        ) : ''
        }
      </>
    );
  }
}
